<template>
	<view class="wrap">
	    <video controls :class="show_view?'video-box':'show_view'" :src="video_url"></video>
		<!-- <ad unit-id="adunit-008c9220b25bdc2a"></ad> -->
	    <button class="parsing" @click="download" style="margin-top: 40rpx;">保存到相册</button>
		<button class="parsing" style="margin-top: 40rpx;margin-bottom: 40rpx;" @click="copy">复制链接</button>
	    <button class="parsing" style="margin-top: 40rpx;margin-bottom: 40rpx;" open-type="share">分享</button>
		<button class="parsing go-back" style="margin-bottom: 40rpx;" @click="go_back">返回</button>
	    <!-- <ad unit-id="adunit-be33d9473f28505f" :class="show_view?'':'show_view'" ad-type="video" ad-theme="white"></ad> -->
	</view>
</template>

<script>
	export default {
		data() {
			return {
				show_view: true,
				providerList: [],
				video: [],
				video_url: '',
				video_title: '',
				video_name_url: ''
			}
		},
		onShareAppMessage(res) {
			if (res.from === 'menu') { // 来自右上角分享按钮
				console.log(res.target)
			}
			if (res.from === 'button') { // 来自页面内分享按钮
				console.log(res.target)
			}
			return {
				title: this.video_title,
				path: '/pages/video/index?query=' + encodeURIComponent(JSON.stringify(this.video))
			}
		},
		onNavigationBarButtonTap(e) {
			if (e.index === 0) {
				// #ifdef APP-PLUS
				if (this.providerList.length === 0) {
					uni.showModal({
						title: '当前环境无分享渠道!',
						showCancel: false
					})
					return;
				}
				let itemList = this.providerList.map(function(value) {
					return value.name
				})
				uni.showActionSheet({
					itemList: itemList,
					success: (res) => {
						uni.share({
							provider: this.providerList[res.tapIndex].id,
							scene: this.providerList[res.tapIndex].type && this.providerList[res.tapIndex].type === 'WXSenceTimeline' ?
								'WXSenceTimeline' : 'WXSceneSession',
							type: 4,
							title: this.video_title,
							summary: this.video_title,
							mediaUrl: this.video_url,
							href: '/pages/video/index?query=' + encodeURIComponent(JSON.stringify(this.video)),
							success: (res) => {
								console.log('success:' + JSON.stringify(res));
							},
							fail: (e) => {
								uni.showModal({
									content: '分享失败1:' + e.errMsg,
									showCancel: false
								})
							}
						});
					}
				});
				// #endif
			}
		},
		onLoad(event) {
			// 目前在某些平台参数会被主动 decode，暂时这样处理。
			try {
				this.video = JSON.parse(decodeURIComponent(event.query));
				this.video_url = this.video.data;
				this.video_title = this.video.video_title;
			} catch (error) {
				this.video = JSON.parse(event.query);
				this.video_url = this.video.data;
				this.video_title = this.video.video_title;
			}
			
			uni.setNavigationBarTitle({
				title: this.video_title
			});
			
			/* uni.request({
				url: this.$api_url + '/home/index',
				method: 'POST',
				header: {'content-type': 'application/x-www-form-urlencoded'},
				data: '',
				success: (result) => {
					if (result.statusCode !== 200) {
						return;
					}
					this.show_view = result.data;
					
				},
				fail: (err) => {
					console.log('获取接口返回错误:', err);
				},
			}); */
		},
		methods: {
			go_back() {
				uni.navigateBack({});
			},
			copy() {
				uni.setClipboardData({
				    data: this.video_url,
				    success: function () {
				        uni.showToast({
				        	icon: 'none',
				        	title: '复制成功',
				        })
				    }
				});
			},
			download() {
				if (!this.video_url) {
					uni.showToast({
						icon: 'none',
						title: '没有可下载的视频，视频去水印后才能下载!'
					})
					return;
				}
				// #ifdef MP-WEIXIN
				// 获取用户的当前设置
				uni.getSetting({
				    success(res) {
					    if(!res.authSetting['scope.writePhotosAlbum']) {
						    uni.openSetting({
								success(rs) {
									console.log(rs.authSetting)
									//res.authSetting = {
										//"scope.userInfo": true,
										//"scope.userLocation": true
									//}
								}
						    });
					    }
				    }
				})
				// #endif
				
				// 比如解析出来的视频地址有 v1-dy v2-dy v3-dy ... v9-dy 将此9条或更多加入到自己小程序合法下载域名内
				// 设置匹配数组 
				var matchArr = ['v1-dy.ixigua.com', 'v2-dy.ixigua.com', 'v3-dy.ixigua.com','v4-dy.ixigua.com', 'v5-dy.ixigua.com', 'v6-dy.ixigua.com','v7-dy.ixigua.com', 'v8-dy.ixigua.com', 'v9-dy.ixigua.com'];
				var flag = 0
				for (const i in matchArr) {
				    if (this.video_url.indexOf(matchArr[i])!=-1) {
						// 执行下载逻辑
						// ... 下载逻辑
						flag = 1
						break
				    }
				}
				/* if (!flag) {
					console.log(this.video_url);
					//this.removeWatermark_api();
					//var uid = uni.getStorageSync('uid');
					uni.request({
						url: this.$api_url + '/video/save',
						method: 'POST',
						header: {'content-type': 'application/x-www-form-urlencoded'},
						data: {video_url:this.video_url,sid:sid},
						success: (result) => {
							if (result.statusCode !== 200) {
								return;
							}
							
							if(result.data.code==200) {
								this.video_name_url = result.data.data;
								
								const downloadTask = uni.downloadFile({
									url: this.video_name_url,
									success: (e) => {
										uni.saveVideoToPhotosAlbum({
											filePath: e.tempFilePath,
											success: () => {
												uni.showToast({
													icon: 'none',
													title: '已保存到手机相册'
												})
											},
											fail: () => {
												uni.showToast({
													icon: 'none',
													title: '保存到手机相册失败' + e.tempFilePath
												})
											}
										});
									},
									fail: (e) => {
										uni.showModal({
											content: '下载失败，' + e.errMsg,
											showCancel: false
										})
									}
								});
								downloadTask.onProgressUpdate((res) => {
									//console.log('下载进度' + res.progress);
									//console.log('已经下载的数据长度' + res.totalBytesWritten);
									//console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
									
									uni.showLoading({
										title: '下载进度' + res.progress + '%'
									});
									
									// 测试条件，取消下载任务。
									//if (res.progress > 50) {
										//downloadTask.abort();
									//}
								})
								
							}else {
								uni.showToast({
									icon: 'none',
									title: result.data.msg,
								})
							}
							
							console.log(result.data);
						},
						fail: (err) => {
							console.log('获取接口返回错误:', err);
						},
					});
					return;
				    // 执行解析逻辑 继续解析接口 在匹配 直到匹配完成 或 匹配10次未成功则提示 请重新解析
				} */
				
					const downloadTask = uni.downloadFile({
						url: this.video_url,
						success: (e) => {
							uni.saveVideoToPhotosAlbum({
								filePath: e.tempFilePath,
								success: () => {
									uni.showToast({
										icon: 'none',
										title: '已保存到手机相册'
									})
								},
								fail: () => {
									uni.showToast({
										icon: 'none',
										title: '保存到手机相册失败' + e.tempFilePath
									})
								}
							});
						},
						fail: (e) => {
							uni.showModal({
								content: '下载失败，' + e.errMsg,
								showCancel: false
							})
						}
					});
					downloadTask.onProgressUpdate((res) => {
						//console.log('下载进度' + res.progress);
						//console.log('已经下载的数据长度' + res.totalBytesWritten);
						//console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
						
						uni.showLoading({
							title: '下载进度' + res.progress + '%'
						});
						
						// 测试条件，取消下载任务。
						//if (res.progress > 50) {
							//downloadTask.abort();
						//}
					})
				
					//var uid = uni.getStorageSync('uid');
					/* uni.request({
						url: this.$api_url + '/video/save',
						method: 'POST',
						header: {'content-type': 'application/x-www-form-urlencoded'},
						data: {video_url:this.video_url,sid:sid},
						success: (result) => {
							if (result.statusCode !== 200) {
								return;
							}
							
							if(result.data.code==200) {
								this.video_name_url = result.data.data;
								
								const downloadTask = uni.downloadFile({
									url: this.video_name_url,
									success: (e) => {
										uni.saveVideoToPhotosAlbum({
											filePath: e.tempFilePath,
											success: () => {
												uni.showToast({
													icon: 'none',
													title: '已保存到手机相册'
												})
											},
											fail: () => {
												uni.showToast({
													icon: 'none',
													title: '保存到手机相册失败' + e.tempFilePath
												})
											}
										});
									},
									fail: (e) => {
										uni.showModal({
											content: '下载失败，' + e.errMsg,
											showCancel: false
										})
									}
								});
								downloadTask.onProgressUpdate((res) => {
									//console.log('下载进度' + res.progress);
									//console.log('已经下载的数据长度' + res.totalBytesWritten);
									//console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
									
									uni.showLoading({
										title: '下载进度' + res.progress + '%'
									});
									
									// 测试条件，取消下载任务。
									//if (res.progress > 50) {
										//downloadTask.abort();
									//}
								})
								
							}else {
								uni.showToast({
									icon: 'none',
									title: result.data.msg,
								})
							}
							
							console.log(result.data);
						},
						fail: (err) => {
							console.log('获取接口返回错误:', err);
						},
					}); */
				
				/* const downloadTask = uni.downloadFile({
					url: this.video_name_url,
					success: (e) => {
						uni.saveVideoToPhotosAlbum({
							filePath: e.tempFilePath,
							success: () => {
								uni.showToast({
									icon: 'none',
									title: '已保存到手机相册'
								})
							},
							fail: () => {
								uni.showToast({
									icon: 'none',
									title: '保存到手机相册失败' + e.tempFilePath
								})
							}
						});
					},
					fail: (e) => {
						uni.showModal({
							content: '下载失败，' + e.errMsg,
							showCancel: false
						})
					}
				});
				downloadTask.onProgressUpdate((res) => {
				    //console.log('下载进度' + res.progress);
				    //console.log('已经下载的数据长度' + res.totalBytesWritten);
				    //console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
					
					uni.showLoading({
					    title: '下载进度' + res.progress + '%'
					});
					
				    // 测试条件，取消下载任务。
				    //if (res.progress > 50) {
				        //downloadTask.abort();
				    //}
				}) */
			}
		}
	}
</script>

<style>
	.video-box {
	    display: block;
	    width: 660rpx;
	    height: 800rpx;
	    margin: 40rpx auto;
	}
	
	.parsing {
	    overflow: hidden;
	    display: block;
	    width: 664rpx;
	    height: 88rpx;
	    line-height: 88rpx;
	    color: #fff;
	    background-color: #8A2BE2;
	    box-shadow: 0 14rpx 28rpx rgba(51,122,255,.3);
	}
	
	.go-back {
	    color: #000;
	    background-color: #F8F8F8;
	    border: 1px solid rgba(5,5,5,.1);
	    box-shadow: none;
	    margin-top: 40rpx;
	}
	
	.show_view {
		display: none !important;;
	}
</style>